package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strings"
	"xinhua_bookstore_db/models"
)

type BooksController struct {
	beego.Controller
}

// 书籍发布
func (c *BooksController) Add() {
	//接收数据
	title := c.GetString("title")
	content := c.GetString("content")
	//验证图书名称和内容
	if title == "" || content == "" {
		res := Response{
			Code: 500,
			Msg:  "图书名称或内容不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	//img
	file, header, err1 := c.GetFile("img")
	if err1 != nil {
		res := Response{
			Code: 500,
			Msg:  "请选择要上传的图片",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	defer file.Close()

	//验证大小
	if header.Size > 3*1024*1024 {
		res := Response{
			Code: 500,
			Msg:  "图片大小不能超过3MB",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	//验证图片格式
	ext := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if ext[suffix] == false {
		res := Response{
			Code: 500,
			Msg:  "图片格式不正确，请选择png、jpg、jpeg格式的图片",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)

	//实例化结构体
	books := models.Books{
		Title:   title,
		Content: content,
		Img:     "http://127.0.0.1:8080/" + path,
	}
	//调用方法，实现添加
	if books.Add() != nil {
		res := Response{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res := Response{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return

}
